Micron Document
Livres et Wikis | Archives | Info


JavaScript syntax
part 15/31 Β· 107.4 KB total
layout: Wide Β· Narrow Β· Centered
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
my_array = "We start at 11:30, 12:15 and 16:45".match(/\d\d:\d\d/g); // my_array==["11:30","12:15","16:45"];

Capturing groups

const myRe = /(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/;
const results = myRe.exec("The date and time are 2009-09-08 09:37:08.");
if (results) {
console.log("Matched: " + results[0]); // Entire match
const my_date = results[1]; // First group == "2009-09-08"
const my_time = results[2]; // Second group == "09:37:08"
console.log(`It is ${my_time} on ${my_date}`);
} else console.log("Did not find a valid date!");

Function

Every function in JavaScript is an instance of the Function constructor:

// x, y is the argument. 'return x + y' is the function body, which is the last in the argument list.
const add = new Function('x', 'y', 'return x + y');
add(1, 2); // => 3

The add function above may also be defined using a function expression:

const add = function(x, y) {
return x + y;
};
add(1, 2); // => 3

In ES6, arrow function syntax was added, allowing functions that return a value to be more concise. They also retain the this of the global object instead of inheriting it from where it was called / what it was called on, unlike the function() {} expression.

const add = (x, y) => {return x + y;};
// values can also be implicitly returned (i.e. no return statement is needed)
const addImplicit = (x, y) => x + y;
add(1, 2); // => 3
addImplicit(1, 2) // => 3

For functions that need to be hoisted, there is a separate expression:

function add(x, y) {
return x + y;
}
add(1, 2); // => 3

Hoisting allows users to use the function before it is "declared":

add(1, 2); // => 3, not a ReferenceError
function add(x, y) {
return x + y;
}

A function instance has properties and methods.

function subtract(x, y) {
return x - y;
}
console.log(subtract.length); // => 2, arity of the function (number of arguments)
console.log(subtract.toString());
/*
"function subtract(x, y) {
return x - y;
}"
*/


──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────